package com.cskaoyan.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.ibatis.type.*;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


/**
 * @program: project-market
 * @description: StringArrayTypeHandler
 * @author: Jesson Guo
 * @create: 2021-11-30 10:58
 **/
@MappedTypes(String[].class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringArrayTypeHandler implements TypeHandler<String[]> {

    ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 输入映射 Integer[] 👉 String
     * @param preparedStatement JDBC做预编译的参数
     * @param index 序号，为预编译Sql语句提供参数的占位符序号
     * select username,password from market_user where username = ? and password = ?
     * @param strings 输入映射传入的值
     * @param jdbcType
     * @throws SQLException
     */

    @SneakyThrows
    @Override
    public void setParameter(PreparedStatement preparedStatement, int index, String[] strings, JdbcType jdbcType) throws SQLException {
        //json
        /*StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[");*/
        String result = objectMapper.writeValueAsString(strings);
        preparedStatement.setString(index,result);
    }

    /**
     * 输出映射  String(查询结果) 👉 Integer[]
     * @param resultSet
     * @return
     * @throws SQLException
     */
    @Override
    public String[] getResult(ResultSet resultSet, String columnName) throws SQLException {
        String result = resultSet.getString(columnName);
        return transfer(result);
    }

    @Override
    public String[] getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String result = resultSet.getString(columnIndex);
        return transfer(result);
    }

    @Override
    public String[] getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String result = callableStatement.getString(columnIndex);
        return transfer(result);
    }

    @SneakyThrows
    private String[] transfer(String result) {
        if (result == null || "".equals(result)) {
            return new String[0];
        }
        String[] strings = objectMapper.readValue(result, String[].class);
        return strings;

    }

}
